//
//  HomeViewController.m
//  IGOtest
//
//  Created by administrator on 14-2-20.
//  Copyright (c) 2014年 administrator. All rights reserved.
//
#import "HomeViewController.h"
#import "GoodsViewController.h"
#import "Product.h"
#import "ProductRowCell.h"
#import "MyButton.h"
#import "AppDelegate.h"
#import "igoods.h"
#define viewCount 3
#define imageMax  3
#define  GOODSAPI @"http://10.207.1.23:8888/user/goods.php"
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
     NSMutableArray *shops;
    AppDelegate *del;
    
}
@property (nonatomic, strong) NSMutableArray *products;

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    del =  [[UIApplication sharedApplication]delegate ];
    index = 0;
    self.shopTableView.delegate=self;
    self.shopTableView.dataSource = self;
    del = [[UIApplication sharedApplication ]delegate ];
    CGFloat wide = self.myScrollView.frame.size.width;
    CGFloat height = self.myScrollView.frame.size.height-44;
    
    NSLog(@"------------%.2f,%.2f",wide,height);
    
    arrayImageView = [NSMutableArray array];
    
    for(int i = 0; i < viewCount; i++)
    {
        UIImageView *imageView = [[UIImageView alloc] init];
        
        imageView.frame = CGRectMake(i * wide, 0, wide, height);
        int imageno = i - 1;
        if(imageno < 0){
            imageno = imageMax;
        }
        
        [arrayImageView addObject:imageView];
        
        NSString *strImage = [NSString stringWithFormat:@"0%i.jpg",imageno ];
        
        imageView.image = [UIImage imageNamed:strImage];
        
        [self.myScrollView addSubview:imageView];
    }
    
    self.myScrollView.contentSize = CGSizeMake(viewCount * wide, height);
    
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.showsVerticalScrollIndicator = NO;
    
    self.myScrollView.pagingEnabled = YES;
    
    self.myScrollView.delegate = self;
    
    self.myScrollView.contentOffset = CGPointMake(320, 0);
    
    //设置UIPageControl
    pageControl = [[UIPageControl alloc] init];
    
    pageControl.center = CGPointMake(wide / 2, height + 35);
    
    pageControl.bounds = CGRectMake(0, 0, 200, 50);
    
    
    pageControl.numberOfPages = imageMax + 1;
    
    pageControl.pageIndicatorTintColor = [UIColor blackColor];
    
    pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
    
    
    [self.view addSubview:pageControl];
    
    
    pageControl.enabled = NO;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singleTap setNumberOfTapsRequired:1];
    
    [_myScrollView addGestureRecognizer:singleTap];
    
    NSURL *url = [NSURL URLWithString:GOODSAPI];
    //定义请求
    NSURLRequest *goodsRequest = [[NSURLRequest alloc]initWithURL:url];
    NSError *error = nil;
    //发送商品请求（同步）,返回NSData类型的请求数据
    NSData *data = [NSURLConnection sendSynchronousRequest:goodsRequest returningResponse:nil error:&error];
    //JSon解析，解析结果为字典
    NSArray *goodsArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"%@",goodsArr);
    del.dataList = [NSMutableArray array];
    if (goodsArr != nil) {
        for (int i=0;i<[goodsArr count];i++) {
            NSDictionary *goods = goodsArr[i];
            NSString *name = [goods objectForKey:@"goodsname"];
            NSString *price = [goods objectForKey:@"price"];
            NSString *comment = [goods objectForKey:@"comment"];
            NSString *image = [goods objectForKey:@"image"];
            NSURL *url = [[NSURL alloc]initWithString:image];
            NSData *imageData = [[NSData alloc]initWithContentsOfURL:url];
            //UIImage *img2 = [[UIImage alloc] initWithContentsOfFile:image];
            UIImage *img = [UIImage imageWithData:imageData];
            igoods *thegoods = [[igoods alloc]initWithGoodsname:name igoodsprice:price igoodscomment:comment igoodsimage:img];
            [del.dataList addObject:thegoods];
            NSLog(@"====%@",del.dataList);
            
        }
    }
    [self creattableview];
}

-(void)creattableview
{
    // 不能选中行
    _shopTableView.allowsSelection = NO;
    
    // 初始化产品数据
    self.products = [NSMutableArray array];
    for (int i = 0; i<=8; i++) {
        // 初始化产品对象
//        Product *p = [[Product alloc] init];
        
        // 设置产品名称
        UIImage *icon =[[del.dataList objectAtIndex:i] igoodsimage];
        NSString *name = [[del.dataList objectAtIndex:i]igoodsname];
       // 设置产品图标
//        int iconIndex = arc4random_uniform(11) + 1;
//        int iconIndex = arc4random_uniform(del.dataList.count);
        Product *theproduct = [[Product alloc]initWithIcon:icon name:name];
//        p.icon = [NSString stringWithFormat:@"tmall_icon_cat_outing_%d.png", iconIndex];
//
        // 添加产品
//        NSLog(@"===%@",del.dataList);
        [self.products addObject:theproduct];
    }

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (self.products.count + kColumn - 1) / kColumn;
}
#pragma mark 每当有一个cell进入视野范围内就会调用，返回当前这行显示的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0.用static修饰的局部变量，只会初始化一次
    static NSString *ID = @"cell";
    
    // 1.拿到一个标识先去缓存池中查找对应的Cell
    ProductRowCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 2.如果缓存池中没有，才需要传入一个标识创建新的Cell
    if (cell == nil) {
       
        cell = [[ProductRowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID withCellRow:indexPath.row];
    }
    // 3.截取这行Cell所需的产品数据
    int location = indexPath.row * kColumn;
    int length = kColumn;
    if (location + length >= self.products.count) {
        length = self.products.count - location;
    }
    NSRange range = NSMakeRange(location, length);
    NSArray *rowProducts = [self.products subarrayWithRange:range];
    // 设置这个行Cell所需的产品数据
    [cell setRowProducts:rowProducts withCellRow:indexPath.row];
    
    for (int i=1; i<=self.products.count; i++) {
        int tag=i +99 + indexPath.row * 3;
        MyButton *btn=(MyButton *)[cell viewWithTag:tag];
        [btn addTarget:self action:@selector(showDetailGood:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
    
}
-(void)showDetailGood:(UIButton *)btn
{
    
    GoodsdetViewController *goodsdet = [[GoodsdetViewController alloc]initWithNibName:@"GoodsdetViewController" bundle:nil ];
//    goodsdet.goods = self.products[btn.tag ];
    NSLog(@"%i",btn.tag);
    goodsdet.goods = del.dataList[btn.tag - 100];

    
    
    [self presentViewController:goodsdet animated:YES completion:nil];
    
}
#pragma mark 每一行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCellHeight;
}

- (void) handleSingleTap:(UITapGestureRecognizer *) gestureRecognizer
{
	CGFloat pageWith = 320;
    
    CGPoint loc = [gestureRecognizer locationInView:_myScrollView];
    NSInteger touchIndex = floor(loc.x / pageWith) ;
    if (touchIndex > 4) {
        return;
    }
    NSLog(@"touch index %d",touchIndex);
    GoodsViewController *goodsCtrl = [[GoodsViewController alloc]initWithNibName:@"GoodsViewController" bundle:nil ];
    [self presentViewController:goodsCtrl animated:YES completion:nil  ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initImageView
{
    imageView1 = [arrayImageView objectAtIndex:0];
    imageView2 = [arrayImageView objectAtIndex:1];
    imageView3 = [arrayImageView objectAtIndex:2];
}

#pragma mark -滑动操作
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //向左滑动
    if(self.myScrollView.contentOffset.x == 640)
    {
        [self initImageView];
        imageView1.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", index % (imageMax + 1)]];
        imageView2.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", (index + 1) % (imageMax + 1)]];
        imageView3.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", (index + 2) % (imageMax + 1)]];
        
        index++;
        
        self.myScrollView.contentOffset = CGPointMake(320, 0);
    }
    
    //向右滑动
    
    if(self.myScrollView.contentOffset.x == 0)
    {
        [self initImageView];
        
        if(index - 2 < 0)
        {
            index = index + imageMax + 1;
        }
        
        imageView1.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", (index - 2) % (imageMax + 1)]];
        imageView2.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", (index - 1) % (imageMax + 1)]];
        imageView3.image = [UIImage imageNamed:[NSString stringWithFormat:@"0%i.jpg", index % (imageMax + 1)]];
        
        index--;
        
        self.myScrollView.contentOffset = CGPointMake(320, 0);
    }
    
    pageControl.currentPage = index % (imageMax + 1);
}
@end